package com.lemon.springboot.controller;

import com.lemon.springboot.config.ApmConfig;
import com.lemon.springboot.dao.IMachineDao;
import com.lemon.springboot.entity.AccountVo;
import com.lemon.springboot.entity.OverviewVo;
import com.lemon.springboot.entity.Result;
import com.lemon.springboot.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Author liuli
 * @Date 2020/12/18 2:48
 */
@Controller
public class SettingController {
    Logger logger = LoggerFactory.getLogger(SettingController.class);
    @Autowired
    ApmConfig apmConfig;

    @Autowired
    IMachineDao machineDao;

    @RequestMapping("/setting")
    public String setting(HttpServletRequest request, Model model){
        List<OverviewVo> tokenVo = machineDao.findUploadTokenByAcc(((AccountVo) request.getSession().getAttribute("account")).getAccount());
        if (tokenVo != null && tokenVo.size() > 0) {
            model.addAttribute("data", tokenVo);
        }
        return "apm-setting";
    }

    @RequestMapping(path = "/delToken", method = RequestMethod.POST)
    public @ResponseBody Result delToken(HttpServletRequest request, @RequestBody Map<String,String> param){
        String token = param.get("token");
        Result result = new Result();
        if (checkAccount(request)) {
            return result.setCodeAndMessage("203", "演示账号禁止操作");
        }
        int count = machineDao.delMachine(token);
        if (count == 1) {
            result.setCodeAndMessage("200", "success");
        }else {
            result.setCodeAndMessage("201", "删除失败");
        }
        return result;
    }

    @RequestMapping(path = "/createToken", method = RequestMethod.POST)
    public @ResponseBody Result createToken(HttpServletRequest request){
        Result result = new Result();
        if (checkAccount(request)) {
            return result.setCodeAndMessage("203", "演示账号禁止操作");
        }
        String token = MD5Util.getUUIDToMD5();
        int count = machineDao.createToken(((AccountVo) request.getSession().getAttribute("account")).getAccount(),token);
        if (count == 1) {
            result.setCodeAndMessage("200", "success");
        }else {
            result.setCodeAndMessage("201", "生成失败");
        }
        return result;
    }

    @RequestMapping("/downloadProbe/{type}")
    public void downloadProbe(@PathVariable("type") String type, HttpServletResponse response) {
        String filename = apmConfig.getLocation() + type;
        Result result = new Result();
        File file = new File(filename);
        logger.info("filename:{}", filename);
        // 如果文件存在，则进行下载
        if (file.exists()) {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            // 配置文件下载
            try {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(type, "UTF-8"));
                // 实现文件下载
                byte[] buffer = new byte[1024];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                logger.info("Download success. file name:{}", type);
            } catch (Exception e) {
                logger.error("Download  failed!", e);
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        logger.error("Download  failed!", e);
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        logger.error("Download  failed!", e);
                    }
                }
            }
        }
    }

    // 演示账号禁止操作
    private boolean checkAccount(HttpServletRequest request){
        if (((AccountVo) request.getSession().getAttribute("account")).getAccount().equals("abc")) {
            return true;
        }
        return false;
    }
}
